package com.csaba.connector.otp.parser;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.htmlparser.jericho.Attribute;
import net.htmlparser.jericho.Attributes;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.TextExtractor;

import com.csaba.connector.model.Customer;

public class AddressParser
{
	private final static Map<String, String> ADDRESS_FIELD_MAP = new HashMap<String, String>();
	static
	{
		ADDRESS_FIELD_MAP.put("Név", "cim1");
		ADDRESS_FIELD_MAP.put("Település", "varos");
		ADDRESS_FIELD_MAP.put("Cím", "cim5");
		ADDRESS_FIELD_MAP.put("Irányítószám", "iranyitoszam");
		ADDRESS_FIELD_MAP.put("Ország", "orszag");
		ADDRESS_FIELD_MAP.put("Postafiók", "postafiok");
		ADDRESS_FIELD_MAP.put("Levelezés módja", "levelezes");
	}

	public static Map<String, String> parseProfile( final Reader reader ) throws IOException, ParseException
	{
		final Source source = new Source(reader);

		// find the account table
		Element form = source.getNextElement(0, HTMLElementName.FORM);
		while ( form != null
				&& ( form.getAttributeValue("name") == null || !form.getAttributeValue("name").equals(
						"levelezesicimModositasForm") ) )
		{
			form = source.getNextElement(form.getBegin() + 1, HTMLElementName.FORM);
		}
		if ( form == null )
			throw new ParseException("Missing form in the document.", 0);

		final List<Element> inputs = form.getAllElements(HTMLElementName.INPUT);

		if ( inputs == null )
			throw new ParseException("Missing input from form.", 0);

		final Map<String, String> props = new HashMap<String, String>();
		for ( final Element input : inputs )
		{
			final Attributes attributes = input.getAttributes();
			final Attribute type = attributes.get("type");
			if ( !type.getValue().endsWith("hidden") )
			{
				final Attribute name = attributes.get("name");
				if ( name != null )
				{
					final String propertyName = name.getValue();
					final Attribute value = attributes.get("value");
					if ( value != null )
					{
						final String propertyValue = value.getValue().trim();
						if ( propertyValue.length() > 0 )
						{
							props.put(propertyName, propertyValue);
						}
					}
				}
			}
		}

		//process further field rows as certain values cannot be edited sometimes.
		final List<Element> divs = form.getAllElementsByClass("fieldrow");
		if ( divs != null )
		{
			for ( final Element div : divs )
			{
				final List<Element> spans = div.getAllElements(HTMLElementName.SPAN);
				if ( spans != null && spans.size() == 1 )
				{
					final String name = new TextExtractor(spans.get(0)).toString();
					if ( name == null || name.trim().length() == 0 )
						continue;

					String value = new TextExtractor(div.getContent()).toString();
					value = value.substring(name.length()).trim();

					final String mappedName = ADDRESS_FIELD_MAP.get(name);

					//map values
					props.put(mappedName == null ? name : mappedName, value);
				}
			}
		}
		return props;
	}

	public final static void setCustomerFields( final Customer customer, final Map<String, String> map )
	{
		for ( final String key : map.keySet() )
		{
			if ( key.equals("cim1") )
			{
				customer.setName(map.get(key));
			}
			else
			{
				customer.setRemoteProperty(key, map.get(key));
			}
		}
	}

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main( final String[] args ) throws Exception
	{
		final Map<String, String> map = parseProfile(new InputStreamReader(new FileInputStream(
				"../otp.source/addressReply2.txt"), OTPCodes.HTML_CHARSET));
		System.out.println("Number of fields: " + map.values().size());
		for ( final String key : map.keySet() )
		{
			System.out.println(key + "=" + map.get(key));
		}

	}

}
